<template>
  <div class="store-performance">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">📊 门店业绩统计</span>
          <div class="header-actions">
            <el-button type="warning" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出报表
            </el-button>
            <el-button type="primary" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
          </div>
        </div>
      </template>

      <!-- 筛选区域 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="所属门店">
          <el-select v-model="searchForm.storeId" placeholder="请选择门店" clearable>
            <el-option label="全部门店" value="" />
            <el-option label="深圳旗舰店" value="1" />
            <el-option label="上海陆家嘴店" value="2" />
            <el-option label="北京国贸店" value="3" />
            <el-option label="广州天河店" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="统计周期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="统计维度">
          <el-select v-model="searchForm.dimension" placeholder="请选择维度">
            <el-option label="按日" value="day" />
            <el-option label="按周" value="week" />
            <el-option label="按月" value="month" />
            <el-option label="按季度" value="quarter" />
            <el-option label="按年" value="year" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 业绩总览卡片 -->
      <el-row :gutter="20" class="stat-cards">
        <el-col :xs="12" :sm="8" :md="4">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
              <el-icon :size="28"><TrendCharts /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">总销售额</div>
              <div class="stat-value">¥{{ (totalSales / 10000).toFixed(1) }}万</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="8" :md="4">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
              <el-icon :size="28"><ShoppingCart /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">订单总数</div>
              <div class="stat-value">{{ totalOrders }}</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="8" :md="4">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
              <el-icon :size="28"><Money /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">客单价</div>
              <div class="stat-value">¥{{ avgOrderValue }}</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="8" :md="4">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
              <el-icon :size="28"><User /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">客流量</div>
              <div class="stat-value">{{ totalCustomers }}</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="8" :md="4">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">
              <el-icon :size="28"><Promotion /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">转化率</div>
              <div class="stat-value">{{ conversionRate }}%</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="8" :md="4">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);">
              <el-icon :size="28"><Star /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">满意度</div>
              <div class="stat-value">{{ satisfaction }}</div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="20" class="chart-row">
        <!-- 销售趋势图 -->
        <el-col :xs="24" :md="12">
          <el-card>
            <template #header>
              <span class="chart-title">📈 销售趋势</span>
            </template>
            <div class="chart-container" ref="salesTrendChartRef"></div>
          </el-card>
        </el-col>

        <!-- 门店业绩排行 -->
        <el-col :xs="24" :md="12">
          <el-card>
            <template #header>
              <span class="chart-title">🏆 门店业绩排行</span>
            </template>
            <div class="chart-container" ref="storeRankChartRef"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="chart-row">
        <!-- 商品类别销售占比 -->
        <el-col :xs="24" :md="12">
          <el-card>
            <template #header>
              <span class="chart-title">📦 商品类别销售占比</span>
            </template>
            <div class="chart-container" ref="categoryChartRef"></div>
          </el-card>
        </el-col>

        <!-- 销售时段分布 -->
        <el-col :xs="24" :md="12">
          <el-card>
            <template #header>
              <span class="chart-title">⏰ 销售时段分布</span>
            </template>
            <div class="chart-container" ref="timeChartRef"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 详细数据表格 -->
      <el-card>
        <template #header>
          <span class="chart-title">📋 详细业绩数据</span>
        </template>
        <el-table :data="tableData" border stripe show-summary>
          <el-table-column prop="storeName" label="门店名称" width="150" />
          <el-table-column prop="sales" label="销售额" width="120" align="right">
            <template #default="{ row }">
              <span class="sales-amount">¥{{ row.sales.toLocaleString() }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="orderCount" label="订单数" width="100" align="center" />
          <el-table-column prop="avgOrderValue" label="客单价" width="100" align="right">
            <template #default="{ row }">
              ¥{{ row.avgOrderValue }}
            </template>
          </el-table-column>
          <el-table-column prop="customerCount" label="客流量" width="100" align="center" />
          <el-table-column prop="conversionRate" label="转化率" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.conversionRate >= 30 ? 'success' : 'warning'">
                {{ row.conversionRate }}%
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="returnRate" label="退货率" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.returnRate <= 3 ? 'success' : 'danger'">
                {{ row.returnRate }}%
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="profit" label="利润" width="120" align="right">
            <template #default="{ row }">
              <span style="color: #67c23a; font-weight: bold;">
                ¥{{ row.profit.toLocaleString() }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="profitRate" label="利润率" width="100" align="center">
            <template #default="{ row }">
              {{ row.profitRate }}%
            </template>
          </el-table-column>
          <el-table-column prop="growth" label="同比增长" width="100" align="center">
            <template #default="{ row }">
              <span :style="{ color: row.growth >= 0 ? '#67c23a' : '#f56c6c' }">
                {{ row.growth >= 0 ? '+' : '' }}{{ row.growth }}%
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleViewDetail(row)">查看详情</el-button>
              <el-button link type="success" @click="handleViewDashboard(row)">数据看板</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Download, Refresh, TrendCharts, ShoppingCart, Money, User, Promotion, Star
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'

const router = useRouter()

// 搜索表单
const searchForm = reactive({
  storeId: '',
  dateRange: [],
  dimension: 'day'
})

// 统计数据
const totalSales = ref(12567890)
const totalOrders = ref(8456)
const avgOrderValue = ref(1487)
const totalCustomers = ref(25678)
const conversionRate = ref(32.9)
const satisfaction = ref(4.8)

// 表格数据
const tableData = ref([
  {
    storeName: '深圳旗舰店',
    sales: 2456789,
    orderCount: 1645,
    avgOrderValue: 1494,
    customerCount: 5234,
    conversionRate: 31.4,
    returnRate: 2.3,
    profit: 615000,
    profitRate: 25.0,
    growth: 15.8
  },
  {
    storeName: '上海陆家嘴店',
    sales: 1987654,
    orderCount: 1328,
    avgOrderValue: 1497,
    customerCount: 4156,
    conversionRate: 32.0,
    returnRate: 1.8,
    profit: 497000,
    profitRate: 25.0,
    growth: 12.5
  },
  {
    storeName: '北京国贸店',
    sales: 2234567,
    orderCount: 1489,
    avgOrderValue: 1501,
    customerCount: 4789,
    conversionRate: 31.1,
    returnRate: 2.1,
    profit: 558000,
    profitRate: 25.0,
    growth: 18.3
  },
  {
    storeName: '广州天河店',
    sales: 1234567,
    orderCount: 834,
    avgOrderValue: 1480,
    customerCount: 2678,
    conversionRate: 31.2,
    returnRate: 2.9,
    profit: 308000,
    profitRate: 25.0,
    growth: -3.2
  }
])

// 图表引用
const salesTrendChartRef = ref(null)
const storeRankChartRef = ref(null)
const categoryChartRef = ref(null)
const timeChartRef = ref(null)

// 搜索
const handleSearch = () => {
  console.log('搜索:', searchForm)
  ElMessage.success('查询成功')
}

// 重置
const handleReset = () => {
  searchForm.storeId = ''
  searchForm.dateRange = []
  searchForm.dimension = 'day'
  handleSearch()
}

// 刷新
const handleRefresh = () => {
  ElMessage.success('数据刷新成功')
}

// 导出
const handleExport = () => {
  ElMessage.success('正在导出报表')
}

// 查看详情
const handleViewDetail = (row) => {
  ElMessage.info(`查看 ${row.storeName} 详细数据`)
}

// 查看看板
const handleViewDashboard = (row) => {
  router.push({
    path: '/store/dashboard',
    query: { storeName: row.storeName }
  })
}

// 初始化销售趋势图
const initSalesTrendChart = () => {
  const chart = echarts.init(salesTrendChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['销售额', '订单量']
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: [
      {
        type: 'value',
        name: '销售额(万元)',
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '订单量',
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '销售额',
        type: 'line',
        data: [120, 132, 101, 134, 90, 230, 210, 250, 198, 276, 245, 310],
        smooth: true,
        itemStyle: { color: '#409eff' }
      },
      {
        name: '订单量',
        type: 'bar',
        yAxisIndex: 1,
        data: [620, 732, 501, 734, 490, 1230, 1110, 1350, 998, 1276, 1145, 1510],
        itemStyle: { color: '#67c23a' }
      }
    ]
  }
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化门店排行图
const initStoreRankChart = () => {
  const chart = echarts.init(storeRankChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: ['成都店', '广州店', '上海店', '北京店', '深圳店']
    },
    series: [
      {
        type: 'bar',
        data: [123, 145, 198, 223, 245],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#667eea' },
            { offset: 1, color: '#764ba2' }
          ])
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c}万元'
        }
      }
    ]
  }
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化类别销售图
const initCategoryChart = () => {
  const chart = echarts.init(categoryChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}万元 ({d}%)'
    },
    legend: {
      bottom: 10,
      left: 'center'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        data: [
          { value: 456, name: '手机', itemStyle: { color: '#667eea' } },
          { value: 345, name: '电脑', itemStyle: { color: '#f093fb' } },
          { value: 234, name: '平板', itemStyle: { color: '#4facfe' } },
          { value: 178, name: '配件', itemStyle: { color: '#43e97b' } },
          { value: 123, name: '其他', itemStyle: { color: '#fa709a' } }
        ]
      }
    ]
  }
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化时段分布图
const initTimeChart = () => {
  const chart = echarts.init(timeChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['9:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00']
    },
    yAxis: {
      type: 'value',
      name: '销售额(万元)'
    },
    series: [
      {
        type: 'line',
        data: [12, 18, 25, 32, 28, 35, 42, 48, 55, 62, 58, 45],
        smooth: true,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64, 158, 255, 0.5)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
          ])
        },
        itemStyle: { color: '#409eff' }
      }
    ]
  }
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 组件挂载
onMounted(() => {
  nextTick(() => {
    initSalesTrendChart()
    initStoreRankChart()
    initCategoryChart()
    initTimeChart()
  })
})
</script>

<style scoped>
.store-performance {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

/* 统计卡片 */
.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s;
  margin-bottom: 20px;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-right: 12px;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

/* 图表区域 */
.chart-row {
  margin-bottom: 20px;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
}

.chart-container {
  width: 100%;
  height: 300px;
}

/* 销售金额 */
.sales-amount {
  color: #f56c6c;
  font-weight: bold;
}
</style>

